﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Portal.Nhibernate.Repository;

namespace Portal.Web.Admin
{
    public partial class Login : BasePage
    {
        private readonly IRepository<IUser> _userRepository;
        private const string LoginCodeSessionKey = "LoginCodeSessionKey";
        public Login()
        {
            _userRepository = new UserRepository();
        }
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Request.IsAjaxRequest())
            {
                var userName = Request.Form["userName"];
                var password = Request.Form["password"];
                var code = Request.Form["code"];
                if (string.IsNullOrEmpty(userName.NullSafe().Trim()))
                    Json(new AjaxResult { state = false, message = "用户名不能为空" });
                if (string.IsNullOrEmpty(password.NullSafe().Trim()))
                    Json(new AjaxResult { state = false, message = "密码不能为空" });
                if (string.IsNullOrEmpty(code.NullSafe().Trim()))
                    Json(new AjaxResult { state = false, message = "验证码为空" });
                if (Session["code"] != null && code.ToLower() != Session[LoginCodeSessionKey].ToString().ToLower())
                    Json(new AjaxResult { state = false, message = "验证码输入不正确,请重输" });
                var model = _userRepository.Get().SingleOrDefault(o => o.Account == userName && o.Password == password);
                if (model == null)
                {
                    Session["code"] = null;
                    Json(new AjaxResult { state = false, message = "用户名或者密码错误" });
                }
                //加入from验证票据
                FormsAuthentication.SetAuthCookie(userName, true);
                Json(new AjaxResult { state = true, message = "登入成功" });
            }
        }

    }
}